/*
 * UART.c - UART驱动实现文件
 * 适用于MSPM0G3507微控制器
 */

#include "UART.h"
#include <string.h>

// 私有函数声明
static void UART_BufferInit(UART_TxBuffer_t *txBuf, UART_RxBuffer_t *rxBuf);
static bool UART_TxBufferPut(UART_TxBuffer_t *buffer, uint8_t data);
static bool UART_TxBufferGet(UART_TxBuffer_t *buffer, uint8_t *data);
static bool UART_RxBufferPut(UART_RxBuffer_t *buffer, uint8_t data);
static bool UART_RxBufferGet(UART_RxBuffer_t *buffer, uint8_t *data);
static uint16_t UART_TxBufferFreeSpace(const UART_TxBuffer_t *buffer);
static uint16_t UART_RxBufferDataCount(const UART_RxBuffer_t *buffer);
static void UART_EnableInterrupts(UART_Handle_t *handle, bool txEnable, bool rxEnable);

/**
 * @brief 初始化UART驱动
 */
UART_Status_t UART_Init(UART_Handle_t *handle, const UART_Config_t *config)
{
    if (handle == NULL || config == NULL) {
        return UART_STATUS_ERROR;
    }

    // 设置UART实例
    handle->instance = config->instance;
    
    // 初始化缓冲区
    UART_BufferInit(&handle->txBuffer, &handle->rxBuffer);
    
    // 清除忙标志
    handle->txBusy = false;
    handle->rxBusy = false;
    
    // 启用中断（如果需要）
    UART_EnableInterrupts(handle, config->enableTxInterrupt, config->enableRxInterrupt);
    
    return UART_STATUS_SUCCESS;
}

/**
 * @brief 发送单个字节
 */
UART_Status_t UART_SendByte(UART_Handle_t *handle, uint8_t data)
{
    if (handle == NULL) {
        return UART_STATUS_ERROR;
    }

    // 尝试直接发送（如果FIFO不满）
    if (!DL_UART_Main_isTXFIFOFull(handle->instance)) {
        DL_UART_Main_transmitData(handle->instance, data);
        return UART_STATUS_SUCCESS;
    }
    
    // FIFO满，尝试放入缓冲区
    if (UART_TxBufferPut(&handle->txBuffer, data)) {
        // 启用发送中断
        DL_UART_Main_enableInterrupt(handle->instance, DL_UART_MAIN_INTERRUPT_TX);
        return UART_STATUS_SUCCESS;
    }
    
    return UART_STATUS_BUFFER_FULL;
}

/**
 * @brief 发送数据缓冲区
 */
UART_Status_t UART_SendData(UART_Handle_t *handle, const uint8_t *data, uint16_t length)
{
    if (handle == NULL || data == NULL || length == 0) {
        return UART_STATUS_ERROR;
    }

    UART_Status_t status = UART_STATUS_SUCCESS;
    for (uint16_t i = 0; i < length; i++) {
        status = UART_SendByte(handle, data[i]);
        if (status != UART_STATUS_SUCCESS) {
            break;
        }
    }
    
    return status;
}

/**
 * @brief 发送字符串
 */
UART_Status_t UART_SendString(UART_Handle_t *handle, const char *str)
{
    if (handle == NULL || str == NULL) {
        return UART_STATUS_ERROR;
    }

    return UART_SendData(handle, (const uint8_t *)str, strlen(str));
}

/**
 * @brief 接收单个字节
 */
UART_Status_t UART_ReceiveByte(UART_Handle_t *handle, uint8_t *data)
{
    if (handle == NULL || data == NULL) {
        return UART_STATUS_ERROR;
    }

    // 尝试从接收缓冲区获取数据
    if (UART_RxBufferGet(&handle->rxBuffer, data)) {
        return UART_STATUS_SUCCESS;
    }
    
    // 缓冲区为空，尝试直接从FIFO读取
    if (!DL_UART_Main_isRXFIFOEmpty(handle->instance)) {
        *data = DL_UART_Main_receiveData(handle->instance);
        return UART_STATUS_SUCCESS;
    }
    
    return UART_STATUS_BUFFER_EMPTY;
}

/**
 * @brief 接收数据到缓冲区
 */
UART_Status_t UART_ReceiveData(UART_Handle_t *handle, uint8_t *data, uint16_t length, uint16_t *receivedLength)
{
    if (handle == NULL || data == NULL || receivedLength == NULL) {
        return UART_STATUS_ERROR;
    }

    *receivedLength = 0;
    UART_Status_t status = UART_STATUS_SUCCESS;
    
    for (uint16_t i = 0; i < length; i++) {
        status = UART_ReceiveByte(handle, &data[i]);
        if (status == UART_STATUS_SUCCESS) {
            (*receivedLength)++;
        } else {
            break;
        }
    }
    
    return (*receivedLength > 0) ? UART_STATUS_SUCCESS : status;
}

/**
 * @brief 获取接收缓冲区中的数据数量
 */
uint16_t UART_GetRxDataCount(UART_Handle_t *handle)
{
    if (handle == NULL) {
        return 0;
    }
    
    return UART_RxBufferDataCount(&handle->rxBuffer);
}

/**
 * @brief 获取发送缓冲区中的空闲空间
 */
uint16_t UART_GetTxFreeSpace(UART_Handle_t *handle)
{
    if (handle == NULL) {
        return 0;
    }
    
    return UART_TxBufferFreeSpace(&handle->txBuffer);
}

/**
 * @brief 清空接收缓冲区
 */
void UART_FlushRxBuffer(UART_Handle_t *handle)
{
    if (handle == NULL) {
        return;
    }
    
    handle->rxBuffer.head = 0;
    handle->rxBuffer.tail = 0;
    handle->rxBuffer.count = 0;
}

/**
 * @brief 清空发送缓冲区
 */
void UART_FlushTxBuffer(UART_Handle_t *handle)
{
    if (handle == NULL) {
        return;
    }
    
    handle->txBuffer.head = 0;
    handle->txBuffer.tail = 0;
    handle->txBuffer.count = 0;
}

/**
 * @brief UART中断处理函数
 */
void UART_IRQHandler(UART_Handle_t *handle)
{
    if (handle == NULL) {
        return;
    }

    uint32_t interruptStatus = DL_UART_Main_getPendingInterrupt(handle->instance);
    
    // 处理接收中断
    if (interruptStatus & DL_UART_MAIN_INTERRUPT_RX) {
        while (!DL_UART_Main_isRXFIFOEmpty(handle->instance)) {
            uint8_t receivedData = DL_UART_Main_receiveData(handle->instance);
            UART_RxBufferPut(&handle->rxBuffer, receivedData);
        }
        DL_UART_Main_clearInterruptStatus(handle->instance, DL_UART_MAIN_INTERRUPT_RX);
    }
    
    // 处理发送中断
    if (interruptStatus & DL_UART_MAIN_INTERRUPT_TX) {
        uint8_t data;
        bool hasPendingData = false;
        
        // 从发送缓冲区取出数据并发送
        while (!DL_UART_Main_isTXFIFOFull(handle->instance) && 
               UART_TxBufferGet(&handle->txBuffer, &data)) {
            DL_UART_Main_transmitData(handle->instance, data);
            hasPendingData = true;
        }
        
        // 如果发送缓冲区为空，禁用发送中断
        if (handle->txBuffer.count == 0) {
            DL_UART_Main_disableInterrupt(handle->instance, DL_UART_MAIN_INTERRUPT_TX);
            handle->txBusy = false;
        }
        
        DL_UART_Main_clearInterruptStatus(handle->instance, DL_UART_MAIN_INTERRUPT_TX);
    }
}

// ========== 私有函数实现 ==========

/**
 * @brief 初始化缓冲区
 */
static void UART_BufferInit(UART_TxBuffer_t *txBuf, UART_RxBuffer_t *rxBuf)
{
    if (txBuf != NULL) {
        txBuf->head = 0;
        txBuf->tail = 0;
        txBuf->count = 0;
        memset(txBuf->buffer, 0, UART_TX_BUFFER_SIZE);
    }
    
    if (rxBuf != NULL) {
        rxBuf->head = 0;
        rxBuf->tail = 0;
        rxBuf->count = 0;
        memset(rxBuf->buffer, 0, UART_RX_BUFFER_SIZE);
    }
}

/**
 * @brief 向发送缓冲区添加数据
 */
static bool UART_TxBufferPut(UART_TxBuffer_t *buffer, uint8_t data)
{
    if (buffer == NULL || buffer->count >= UART_TX_BUFFER_SIZE) {
        return false;
    }
    
    buffer->buffer[buffer->head] = data;
    buffer->head = (buffer->head + 1) % UART_TX_BUFFER_SIZE;
    buffer->count++;
    
    return true;
}

/**
 * @brief 从发送缓冲区获取数据
 */
static bool UART_TxBufferGet(UART_TxBuffer_t *buffer, uint8_t *data)
{
    if (buffer == NULL || data == NULL || buffer->count == 0) {
        return false;
    }
    
    *data = buffer->buffer[buffer->tail];
    buffer->tail = (buffer->tail + 1) % UART_TX_BUFFER_SIZE;
    buffer->count--;
    
    return true;
}

/**
 * @brief 向接收缓冲区添加数据
 */
static bool UART_RxBufferPut(UART_RxBuffer_t *buffer, uint8_t data)
{
    if (buffer == NULL || buffer->count >= UART_RX_BUFFER_SIZE) {
        return false;
    }
    
    buffer->buffer[buffer->head] = data;
    buffer->head = (buffer->head + 1) % UART_RX_BUFFER_SIZE;
    buffer->count++;
    
    return true;
}

/**
 * @brief 从接收缓冲区获取数据
 */
static bool UART_RxBufferGet(UART_RxBuffer_t *buffer, uint8_t *data)
{
    if (buffer == NULL || data == NULL || buffer->count == 0) {
        return false;
    }
    
    *data = buffer->buffer[buffer->tail];
    buffer->tail = (buffer->tail + 1) % UART_RX_BUFFER_SIZE;
    buffer->count--;
    
    return true;
}

/**
 * @brief 获取发送缓冲区空闲空间
 */
static uint16_t UART_TxBufferFreeSpace(const UART_TxBuffer_t *buffer)
{
    if (buffer == NULL) {
        return 0;
    }
    
    return UART_TX_BUFFER_SIZE - buffer->count;
}

/**
 * @brief 获取接收缓冲区数据数量
 */
static uint16_t UART_RxBufferDataCount(const UART_RxBuffer_t *buffer)
{
    if (buffer == NULL) {
        return 0;
    }
    
    return buffer->count;
}

/**
 * @brief 启用/禁用UART中断
 */
static void UART_EnableInterrupts(UART_Handle_t *handle, bool txEnable, bool rxEnable)
{
    if (handle == NULL) {
        return;
    }
    
    if (rxEnable) {
        DL_UART_Main_enableInterrupt(handle->instance, DL_UART_MAIN_INTERRUPT_RX);
        // 设置FIFO阈值
        DL_UART_Main_setRXFIFOThreshold(handle->instance, DL_UART_RX_FIFO_LEVEL_ONE_ENTRY);
    } else {
        DL_UART_Main_disableInterrupt(handle->instance, DL_UART_MAIN_INTERRUPT_RX);
    }
    
    // 发送中断根据需要动态启用/禁用
    if (!txEnable) {
        DL_UART_Main_disableInterrupt(handle->instance, DL_UART_MAIN_INTERRUPT_TX);
    }
}

// UART1中断处理函数已由系统配置文件处理
// 如果需要使用UART中断，请在主程序中调用UART_IRQHandler
